<template>
  <div class="rule-manage">
    <div class="actions">
      <el-button type="primary" @click="openDialog">新增须知</el-button>
    </div>

    <div class="table-wrapper">
      <el-table :data="ruleList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="title" label="标题" width="140" />
        <el-table-column label="图片" width="120">
          <template #default="{ row }: { row: Rule }">
            <el-image
              v-if="row.image"
              :src="row.image"
              style="width: 80px; height: 60px"
              fit="cover"
              @click="previewRowImage(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="link" label="链接地址" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }: { row: Rule }">
            <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
              {{ row.status === 'enabled' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }: { row: Rule }">
            <el-button size="small" @click="editRule(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteRule(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑须知' : '新增须知'"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="标题" required>
          <el-input v-model="form.title" placeholder="请输入须知标题" />
        </el-form-item>

        <el-form-item label="上传图片">
          <el-upload
            class="upload-demo"
            action=""
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleUploadChange"
            :file-list="uploadFileList"
            :on-remove="handleRemove"
            :on-preview="handlePreview"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="链接地址" required>
          <el-input v-model="form.link" placeholder="请输入跳转链接" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRule">保存</el-button>
      </template>
    </el-dialog>

    <el-image-viewer
      v-if="previewVisible"
      :url-list="[previewImage]"
      :initial-index="0"
      @close="previewVisible = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'
import { fetchRules } from '@/api/rule'

type RuleStatus = 'enabled' | 'disabled'
interface Rule {
  id: number
  title: string
  image: string
  link: string
  status: RuleStatus
}

const ruleList = ref<Rule[]>([])
const dialogVisible = ref(false)
const uploadFileList = ref<UploadFile[]>([])
const form = ref<Rule>({
  id: 0,
  title: '',
  image: '',
  link: '',
  status: 'enabled'
})

const previewVisible = ref(false)
const previewImage = ref('')

onMounted(async () => {
  ruleList.value = await fetchRules()
})

function handlePreview(file: UploadFile) {
  previewImage.value = file.url || (file.raw ? URL.createObjectURL(file.raw) : '')
  previewVisible.value = true
}
function previewRowImage(row: Rule) {
  previewImage.value = row.image
  previewVisible.value = true
}
function openDialog() {
  resetForm()
  dialogVisible.value = true
}
function resetForm() {
  form.value = { id: 0, title: '', image: '', link: '', status: 'enabled' }
  uploadFileList.value = []
}
function editRule(row: Rule) {
  form.value = { ...row }
  uploadFileList.value = form.value.image
    ? [{ name: '已上传图片', url: form.value.image } as UploadFile]
    : []
  dialogVisible.value = true
}
function deleteRule(id: number) {
  ruleList.value = ruleList.value.filter(rule => rule.id !== id)
  ElMessage.success('删除成功')
}
function saveRule() {
  if (!form.value.title) return ElMessage.error('请输入须知标题')
  if (!form.value.link) return ElMessage.error('请输入链接地址')

  if (form.value.id) {
    const idx = ruleList.value.findIndex(rule => rule.id === form.value.id)
    if (idx !== -1) ruleList.value[idx] = { ...form.value }
  } else {
    const newId = ruleList.value.length ? Math.max(...ruleList.value.map(r => r.id)) + 1 : 1
    ruleList.value.push({ ...form.value, id: newId })
  }
  ElMessage.success('保存成功')
  dialogVisible.value = false
}
function handleUploadChange(file: UploadFile) {
  if (!file.raw) return
  const reader = new FileReader()
  reader.onload = e => {
    form.value.image = e.target?.result as string
  }
  reader.readAsDataURL(file.raw)
  uploadFileList.value = [file]
}
function handleRemove() {
  form.value.image = ''
  uploadFileList.value = []
}
</script>

<style scoped>
.table-wrapper {
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  overflow-x: auto; /* 保持表格横向滚动可用 */
}
.rule-manage {
  padding: 16px;
}
.actions {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
}
</style>
